package com.equdao.car_violation_inquiry.aspect;

import com.equdao.car_violation_inquiry.exception.NotFindTokenException;
import com.equdao.car_violation_inquiry.pojo.Result;
import com.equdao.car_violation_inquiry.utils.CookieUtil;
import com.equdao.car_violation_inquiry.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: 杨忠强
 * @Date: 2018/7/19 14:32
 * `12390-@Description:/*-
 */
@Aspect
@Component
@Slf4j
public class HttpAspect {
    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

//    @Before("execution(public * com.equdao.car_violation_inquiry.controller.ClientController(..))")
//    public void log(){
//    }

    @Pointcut("execution(public * com.equdao.car_violation_inquiry.controller.ClientController.*(..))")
    public void log(){
    }
    @Pointcut("execution(public * com.equdao.car_violation_inquiry.controller.WebPageController.*(..))")
    public void verify(){
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取请求者的信息
        //url
        StringBuffer url = request.getRequestURL();

        logger.info("url={}" ,url);
        //method
        String method = request.getMethod();
        logger.info("method={}",method);
        //类方法
        String typeName = joinPoint.getSignature().getDeclaringTypeName();
        String name = joinPoint.getSignature().getName();
        logger.info("typeName={}",typeName);
        logger.info("name={}",name);
        //参数
        Object[] args = joinPoint.getArgs();
        logger.info("args={}" , args);
    }

    @Before("verify()")
    public void verify(JoinPoint joinPoint){

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取请求者的信息
        //url

        String doLogin = CookieUtil.getCookie(request, "token");

        if (null == doLogin){
            log.info("[登录校验] Cookie中查不到token");
            throw new NotFindTokenException();

        }




}
//    @After("log()")
//    public void doAfter(){
//        logger.error("执行完毕");
//    }
    @AfterReturning(returning = "object",pointcut = "log()")
    public void doAfterReturning(Object object){
        logger.info("response={}" , object.toString());
    }
}
